<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        #box{width: 100px;height:100px;background: red;position: absolute;left:0px;top:0px;}
    </style>
</head>
<body>
    <div id="box"></div>
</body>
<script>

    class Drag{
        constructor(){
            this.box = document.querySelector("#box")
            // 2. 初始执行程序时，立即读取本地存储，解析数据，设置元素位置
            this.init()
            this.addEvent()
        }
        init(){
            const data = localStorage.getItem("pos");
            this.data = data ? JSON.parse(data) : {}

            this.box.style.left = this.data.x + "px"
            this.box.style.top = this.data.y + "px"
        }
        addEvent(){
            const that = this;
            this.box.addEventListener("mousedown", function(eve){
                that.downE = eve || window.event;
                that.down();
            })
        }
        down(){
            const that = this;
            this.m = function (eve){
                that.moveE = eve || window.event;
                that.move();
            }
            this.u = function(){
                that.up();
            }
            document.addEventListener("mousemove", this.m);
            document.addEventListener("mouseup", this.u);
        }
        move(){
            this.box.style.left = this.moveE.pageX - this.downE.offsetX + "px";
            this.box.style.top = this.moveE.pageY - this.downE.offsetY + "px";
        }
        up(){
            document.removeEventListener("mousemove", this.m)
            document.removeEventListener("mouseup", this.u)

            // 1. 鼠标抬起时，存储当前元素的位置
            this.setData();
        }
        setData(){
            localStorage.setItem("pos", JSON.stringify({
                x:this.box.offsetLeft,
                y:this.box.offsetTop
            }) )
        }
    }


    new Drag();
    
</script>
</html>